package com.crealth.handler;

import java.util.List;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crealth.db.LendingAgencyDb;
import com.crealth.memcached.LendingAgencyCached;
import com.crealth.model.LendingAgencyModel;
import com.crealth.msg.NetMessageData;

public class LendingAgencyHandler {
	
	public static NetMessageData obtainLendingAgency(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();		
		//List<LendingAgencyModel> allAgencyls = LendingAgencyCached.selectAllLendingAgency();
		List<LendingAgencyModel> allAgencyls = LendingAgencyDb.selectAllLendingAgency();
		if (allAgencyls != null && allAgencyls.size() > 0) {			
			JSONArray resJsonArr = new JSONArray();
			for (LendingAgencyModel agency : allAgencyls) {
				resJsonArr.add(agency.toJSONObject());
			}
			
			resJson.put("allAgencyJson", resJsonArr);
		}
		
		resJson.put("resCode", 0);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}

	public static NetMessageData saveLendingAgency(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		String allAgencyJson = msgJson.getString("allAgencyJson");
		JSONArray jsonArray = JSONArray.parseArray(allAgencyJson);
		if (jsonArray != null && jsonArray.size() > 0) {
			JSONArray resJsonArr = new JSONArray();
			for (int i = 0; i < jsonArray.size(); ++i) {
				JSONObject agencyJson = jsonArray.getJSONObject(i);
				LendingAgencyModel agency = new LendingAgencyModel();
				agency.parseFromJson(agencyJson);
				if (agency.getId() > 0) {
					LendingAgencyDb.updateLendingAgency(agency);
				} else {
					LendingAgencyDb.insertLendingAgency(agency);
				}
				resJsonArr.add(agency.toJSONObject());
			}
			
			resJson.put("allAgencyJson", resJsonArr);
			LendingAgencyCached.deleteCached();
		}		
		
		resJson.put("resCode", 0);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	public static NetMessageData delLendingAgency(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int agencyID = msgJson.getIntValue("agencyID");
		Integer res = LendingAgencyDb.deleteLendingAgencyByID(agencyID);
		if (res != null && res == 1) {
			resJson.put("agencyID", agencyID);
			LendingAgencyCached.deleteCached();
		}
		
		resJson.put("resCode", 0);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
}
